//
//  ZCullingViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/2/24.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ZCullingViewController.h"
#import "ZCullingCollectionViewCell.h"
#import "ZCullingDetailViewController.h"
#import "LZPicModel.h"
#import "LZBigPicView.h"

static NSString * const ZCullingViewControllerIdentifier = @"ZCullingViewControllerIdentifier";
@interface ZCullingViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,ZCullingDetailViewControllerDelegate>{
    UICollectionView * _cullingView; //
    UIButton * _uploadButton ; // 上传按钮
    NSMutableArray <LZPicModel *>*_picArray;
    LZPicModel * _lzPicModel;
    // 选中图片数组
    NSMutableArray * _selecPicArr;
    NSString * _type;
}

/** 编辑按钮 */
@property (nonatomic, strong) UIButton *rightBarBtn;
/** collectionView的编辑状态记录 */
@property (nonatomic, strong) NSString *isEdit;

@end

@implementation ZCullingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialzeDatas];
    [self initlizeInterface];
}



- (void)initialzeDatas {
    _picArray = [NSMutableArray array];
    _selecPicArr = [NSMutableArray array];
    _isEdit = @"编辑";
}
- (void)initlizeInterface {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"自己";
    _uploadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_uploadButton setBackgroundColor:MYGREENColor];
    [_uploadButton setTitle:@"上传" forState:UIControlStateNormal];
    [_uploadButton setTintColor:[UIColor whiteColor]];
    [_uploadButton addTarget:self action:@selector(uploadButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UICollectionViewFlowLayout * homeLayout=[[UICollectionViewFlowLayout alloc] init];
    homeLayout.minimumLineSpacing = 5;
    homeLayout.itemSize = CGSizeMake(95 *xsIZE,95*ysIZE);
    homeLayout.sectionInset = UIEdgeInsetsMake(5*xsIZE, 5*xsIZE, 5*xsIZE, 5*xsIZE);
    _cullingView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, 400*ysIZE) collectionViewLayout:homeLayout];
    _cullingView.backgroundColor = KHColorFromRGB(0xf8f8f8f8);
    _cullingView.showsVerticalScrollIndicator = YES;
    _cullingView.delegate = self;
    _cullingView.dataSource = self;
    
    [_cullingView registerClass:[ZCullingCollectionViewCell class] forCellWithReuseIdentifier:ZCullingViewControllerIdentifier];
    [self.view addSubview: _cullingView];
    [self.view addSubview:_uploadButton];
    [_cullingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.width.equalTo(self.view);
        make.height.offset(500*ysIZE);
    }];
    [_uploadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.width.equalTo(self.view);
        make.height.offset(50*ysIZE);
    }];
    [self makerightButton];
   
}
// 设置右边的发布
- (void)makerightButton {
    _rightBarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightBarBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [_rightBarBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    _rightBarBtn.frame = CGRectMake(0, 0, 40, 30);
    [_rightBarBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightButonItem = [[UIBarButtonItem alloc]initWithCustomView:_rightBarBtn];
    self.navigationItem.rightBarButtonItem = rightButonItem;
}

// 点击编辑
- (void)rightBtnClick:(UIButton *)btn {
    if ([_isEdit isEqualToString:@"编辑"]) {
        [btn setTitle:@"完成" forState:UIControlStateNormal];
        [_uploadButton setTitle:@"删除" forState:UIControlStateNormal];
        [_uploadButton setBackgroundColor:[UIColor redColor]];
        _isEdit = @"完成";
        // 刷新collectionView
    }else if([_isEdit isEqualToString:@"完成"]) {
        [_selecPicArr removeAllObjects];
        [btn setTitle:@"编辑" forState:UIControlStateNormal];
        [_uploadButton setTitle:@"上传" forState:UIControlStateNormal];
        [_uploadButton setBackgroundColor:MYGREENColor];
        _isEdit = @"编辑";
    }
    [_cullingView reloadData];
    // 刷新collectionView
    
}
//上传按钮(这里要把档案id和用户id还有type传过去)*******删除上传按钮
- (void)uploadButtonAction:(UIButton *)sender {
    if ([sender.currentTitle isEqualToString:@"上传"]) {
        // 上传按钮
        ZCullingDetailViewController * vc = [[ZCullingDetailViewController alloc] init];
        vc.artID = _fileID;
        vc.uid = _userID;
        vc.type = _type;
        vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    }else {// 删除按钮
        
        NSMutableArray *array = [NSMutableArray array];
        for (NSString *index in _selecPicArr) {
            [array addObject:_picArray[[index integerValue]].pid];
        }
        NSDictionary *paramas = @{@"ids":array};
        [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"File/delImgs" sucessBlock:^(id content) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
            LZLog(@"------批量删除照片数据-------%@",dict);
            if ([dict[@"code"] intValue] == 1) {
            
                _isEdit = @"编辑";
                [_uploadButton setTitle:@"上传" forState:UIControlStateNormal];
                [_uploadButton setBackgroundColor:MYGREENColor];
                [YJProgressHUD showMessage:@"删除成功" inView:self.view];
                NSMutableArray *deleteArray = [[NSMutableArray alloc] initWithCapacity:_selecPicArr.count];
                //成功以后清空装选中照片的数组,刷新数据
                // 记录选中图片的位置加入到数组中
                for (NSString *index in _selecPicArr) {
                    [deleteArray addObject:_picArray[[index integerValue]]];
                }
                // 在选中图片的index中找出对应的模型并且删除
                for (LZPicModel *model in deleteArray) {
                    [_picArray removeObject:model];
                }
                [_selecPicArr removeAllObjects];
                [_cullingView reloadData];
//                if (_freshBlock) {
//                    _freshBlock();
//                }
                // 返回刷新界面
                if (_delegate && [_delegate conformsToProtocol:@protocol(ZCullingViewControllerDelegate)]) {
                    [_delegate refreshCollectionView];
                }
            }else {
                [YJProgressHUD showMessage:@"删除失败" inView:self.view];
            }
        } failure:^(NSError *error) {
            LZLog(@"%@",error);
        }];
    }
}

// 集合视图协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _picArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZCullingCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ZCullingViewControllerIdentifier forIndexPath:indexPath];
    cell.lzPicModel = _picArray[indexPath.row];
    
//    cell.selectPicBtnBlock = ^(BOOL isSelect){
//        if (isSelect) {
//            [_selecPicArr addObject:[NSString stringWithFormat:@"%ld",indexPath.row]];
//        }else {
//            [_selecPicArr removeObject:[NSString stringWithFormat:@"%ld",indexPath.row]];
//        }
//    };
    //是否选中了这个cell的图片
    if ([_selecPicArr containsObject:[NSString stringWithFormat:@"%ld",indexPath.row]]) {
        cell.selectBtn.selected = YES;
    }else {
        cell.selectBtn.selected = NO;
    }
    // 根据编辑按钮的文字判断是否显示删除按钮
    if ([_isEdit isEqualToString:@"编辑"]) {
        cell.selectBtn.hidden = YES;
    }else if ([_isEdit isEqualToString:@"完成"]) {
        cell.selectBtn.hidden = NO;
    }
    return cell;
}

// 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    // 如果不是编辑状态
    if ([_rightBarBtn.currentTitle isEqualToString:@"编辑"]) {
        LZBigPicView *bigPicView = [[LZBigPicView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        bigPicView.lzPicModel = _picArray[indexPath.row];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:bigPicView];
    }else {
        // 如果是编辑状态
        ZCullingCollectionViewCell *zcullingCell = (ZCullingCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
        if (!zcullingCell.selectBtn.selected) {
            [_selecPicArr addObject:[NSString stringWithFormat:@"%ld",indexPath.row]];
            zcullingCell.selectBtn.selected = YES;
        }else {
            [_selecPicArr removeObject:[NSString stringWithFormat:@"%ld",indexPath.row]];
            zcullingCell.selectBtn.selected = NO;
        }
    }
}


// 根据type上传照片
- (void)setType:(NSString *)type {
    NSDictionary *paramas = @{@"id":self.fileID,@"uid":_userID,@"type":type};
    __weak typeof(self) weakSelf = self;
    
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"File/minImg" sucessBlock:^(id content) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"--------缩略图列表数据-----------%@",dict);
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"加载失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            [weakSelf dealDataWithDict:dict];
            // 保存type
            _type = dict[@"type"];
        }
    } failure:^(NSError *error) {
        LZLog(@"%@",error);
    }];
}

// 处理数据拿出照片
- (void)dealDataWithDict:(NSDictionary *)dict {
    [_picArray removeAllObjects];
    NSArray *tempArr = dict[@"list"];
    for (NSDictionary *dict in tempArr) {
        _lzPicModel = [[LZPicModel alloc] initWithDict:[dict mutableCopy]];
        [_picArray addObject:_lzPicModel];
    }
    [_cullingView reloadData];
}
// 上传成功以后刷新界面
- (void)refreshWithType:(NSString *)type {
    [self setType:type];
    if (_delegate && [_delegate respondsToSelector:@selector(refreshCollectionView)]) {
        [_delegate refreshCollectionView];
    }
}



@end
